<template>
  <div class="sd-container">
    <div class="header">
      <h2>{{ batchMode ? '批量图片生成' : '测试图片生成' }}</h2>
      <div class="header-actions">
        <el-button-group>
          <el-button
            type="success"
            @click="handleSaveConfig"
            :disabled="!configName.trim()"
          >保存配置
          </el-button>
        </el-button-group>
      </div>
    </div>

    <div class="content">
      <div class="preview-area">
        <div
          v-for="(msg, index) in messages"
          :key="index"
          class="message"
        >
          <template v-if="msg.type === 'text'">
            <div class="prompt">{{ msg.content }}</div>
          </template>
          <template v-else-if="msg.type === 'image'">
            <img
              :src="'data:image/png;base64,' + msg.content"
              class="generated-image"
              alt="Generated Image"
            />
          </template>
        </div>
      </div>

      <div class="config-area">
        <el-form
          :model="config"
          label-position="top"
        >
          <el-form-item label="配置管理">
            <div class="config-management">
              <el-select
                v-model="selectedConfig"
                placeholder="选择配置"
                @change="handleLoadConfig"
                style="width: 200px"
              >
                <el-option
                  v-for="name in configList"
                  :key="name"
                  :label="name + (name === defaultConfigName ? ' (默认)' : '')"
                  :value="name"
                />
              </el-select>
              <el-input
                v-model="configName"
                placeholder="输入配置名称"
                style="width: 200px; margin-left: 10px"
              />
              <el-button
                type="primary"
                @click="handleSetDefault"
                :disabled="!selectedConfig"
                style="margin-left: 10px"
              >
                设为默认
              </el-button>
            </div>
          </el-form-item>
          <el-form-item label="提示词">
            <el-input
              v-model="prompt"
              type="textarea"
              :rows="4"
              placeholder="请输入提示词..."
              :disabled="generating"
            />
          </el-form-item>

          <el-form-item label="反向提示词">
            <el-input
              v-model="config.negative_prompt"
              type="textarea"
              :rows="2"
              :disabled="generating"
            />
          </el-form-item>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="宽度">
                <el-input-number
                  v-model="config.width"
                  :min="64"
                  :step="64"
                  :disabled="generating"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="高度">
                <el-input-number
                  v-model="config.height"
                  :min="64"
                  :step="64"
                  :disabled="generating"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="模型选择">
                <el-select
                  v-model="config.model"
                  :disabled="generating"
                  placeholder="请选择模型"
                >
                  <el-option
                    v-for="model in modelList"
                    :key="model"
                    :label="model"
                    :value="model"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="种子">
                <el-input-number
                  v-model="config.seed"
                  :min="-1"
                  :max="2147483647"
                  :disabled="generating"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="采样步数">
                <el-input-number
                  v-model="config.steps"
                  :min="1"
                  :max="150"
                  :disabled="generating"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="CFG Scale">
                <el-input-number
                  v-model="config.cfg_scale"
                  :min="1"
                  :max="30"
                  :step="0.5"
                  :disabled="generating"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item label="高清修复">
            <el-switch
              v-model="config.enable_hr"
              :disabled="generating"
            />
          </el-form-item>

          <template v-if="batchMode">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="批次数量">
                  <el-input-number
                    v-model="config.batch_count"
                    :min="1"
                    :max="10"
                    :disabled="generating"
                  />
                  <div class="form-item-help">生成多少批次的图片</div>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="每批数量">
                  <el-input-number
                    v-model="config.batch_size"
                    :min="1"
                    :max="4"
                    :disabled="generating"
                  />
                  <div class="form-item-help">每批生成多少张图片</div>
                </el-form-item>
              </el-col>
            </el-row>
          </template>
          <el-form-item label="高清修复模式" v-if="config.enable_hr">
            <el-radio-group v-model="config.hr_resize_mode" :disabled="generating">
              <el-radio label="scale">使用放大倍率</el-radio>
              <el-radio label="size">指定输出尺寸</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-row
            :gutter="20"
            v-if="config.enable_hr && config.hr_resize_mode === 'scale'"
          >
            <el-col :span="12">
              <el-form-item label="放大倍数">
                <el-slider
                  v-model="config.upscaler_scale"
                  :min="1"
                  :max="4"
                  :step="0.5"
                  :disabled="generating"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="重绘幅度">
                <el-slider
                  v-model="config.denoising_strength"
                  :min="0"
                  :max="1"
                  :step="0.05"
                  :disabled="generating"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row
            :gutter="20"
            v-if="config.enable_hr && config.hr_resize_mode === 'size'"
          >
            <el-col :span="12">
              <el-form-item label="目标宽度">
                <el-input-number
                  v-model="config.hr_target_width"
                  :min="512"
                  :step="64"
                  :disabled="generating"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="目标高度">
                <el-input-number
                  v-model="config.hr_target_height"
                  :min="512"
                  :step="64"
                  :disabled="generating"
                />
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-row :gutter="20" v-if="config.enable_hr">
            <el-col :span="12">
              <el-form-item label="放大方法">
                <el-select
                  v-model="config.upscaler_name"
                  :disabled="generating"
                  placeholder="请选择放大方法"
                >
                  <el-option label="Lanczos" value="Lanczos" />
                  <el-option label="Nearest" value="Nearest" />
                  <el-option label="ESRGAN_4x" value="ESRGAN_4x" />
                  <el-option label="R-ESRGAN 4x+" value="R-ESRGAN 4x+" />
                  <el-option label="LDSR" value="LDSR" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="重绘幅度">
                <el-slider
                  v-model="config.denoising_strength"
                  :min="0"
                  :max="1"
                  :step="0.05"
                  :disabled="generating"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item label="最终输出尺寸" v-if="config.enable_hr">
            <div class="output-size-display">
              {{ config.hr_resize_mode === 'scale' ? 
                 Math.round(config.width * config.upscaler_scale) + ' × ' + Math.round(config.height * config.upscaler_scale) : 
                 config.hr_target_width + ' × ' + config.hr_target_height }}
            </div>
            <div class="form-item-help">高清修复后的最终图像尺寸</div>
          </el-form-item>

          <el-form-item label="Lora模型">
            <el-select
              v-model="config.lora_model"
              :disabled="generating"
              placeholder="请选择Lora模型"
            >
              <el-option
                label="无"
                value=""
              />
              <el-option
                v-for="model in loraModelList"
                :key="model"
                :label="model"
                :value="model"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            label="权重"
            v-if="config.lora_model"
          >
            <el-slider
              v-model="config.lora_weight"
              :min="0"
              :max="1"
              :step="0.05"
              :disabled="generating"
            />
          </el-form-item>

          <el-form-item label="采样器">
            <el-select
              v-model="config.sampler_name"
              :disabled="generating"
              placeholder="请选择采样器"
            >
              <el-option
                label="Euler a"
                value="Euler a"
              />
              <el-option
                label="Euler"
                value="Euler"
              />
              <el-option
                label="LMS"
                value="LMS"
              />
              <el-option
                label="Heun"
                value="Heun"
              />
              <el-option
                label="DPM2"
                value="DPM2"
              />
              <el-option
                label="DPM2 a"
                value="DPM2 a"
              />
              <el-option
                label="DPM++ 2S a"
                value="DPM++ 2S a"
              />
              <el-option
                label="DPM++ 2M"
                value="DPM++ 2M"
              />
              <el-option
                label="DPM++ SDE"
                value="DPM++ SDE"
              />
              <el-option
                label="DPM fast"
                value="DPM fast"
              />
              <el-option
                label="DPM adaptive"
                value="DPM adaptive"
              />
              <el-option
                label="LMS Karras"
                value="LMS Karras"
              />
              <el-option
                label="DPM2 Karras"
                value="DPM2 Karras"
              />
              <el-option
                label="DPM2 a Karras"
                value="DPM2 a Karras"
              />
              <el-option
                label="DPM++ 2S a Karras"
                value="DPM++ 2S a Karras"
              />
              <el-option
                label="DPM++ 2M Karras"
                value="DPM++ 2M Karras"
              />
              <el-option
                label="DPM++ SDE Karras"
                value="DPM++ SDE Karras"
              />
              <el-option
                label="DDIM"
                value="DDIM"
              />
              <el-option
                label="PLMS"
                value="PLMS"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="总批次数">
            <el-input-number
              v-model="config.batch_count"
              :min="1"
              :max="10"
              :step="1"
              :disabled="generating"
            />
            <div class="form-item-help">生成多少批次的图片</div>
          </el-form-item>

          <el-form-item label="单批数量">
            <el-input-number
              v-model="config.batch_size"
              :min="1"
              :max="6"
              :step="1"
              :disabled="generating"
            />
            <div class="form-item-help">一次生成多少张图片（最多6张）</div>
          </el-form-item>
        </el-form>

        <div class="actions">
          <el-button
            type="primary"
            @click="handleGenerate"
            :loading="generating"
            :disabled="!sdServiceAvailable || !prompt.trim()"
          >
            生成图片
          </el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed, watch } from 'vue'
import type { GenerateParams } from '@/services/sd'
import { saveConfig, loadConfig, listConfigs } from '@/services/sd_config'
import { sdApi } from '@/services/sd'
import { ElMessage } from 'element-plus'

const props = defineProps<{
  messages: Array<{
    type: 'text' | 'image'
    content: string
    isUser: boolean
  }>
  generating: boolean
  sdServiceAvailable: boolean
  batchMode?: boolean
}>()

const emit = defineEmits<{
  (e: 'send', data: GenerateParams): void
  (e: 'toggle-batch'): void
}>()

const batchMode = computed(() => props.batchMode || false)

const defaultConfigTemplate = {
  negative_prompt: '',
  width: 512,
  batch_count: 1,
  batch_size: 4,
  height: 512,
  steps: 20,
  cfg_scale: 7,
  sampler_name: 'Euler a',
  model: '',
  seed: -1,
  enable_hr: false,
  denoising_strength: 0.7,
  upscaler_scale: 2,
  upscaler_name: 'Lanczos',
  lora_model: '',
  lora_weight: 0.5,
  batch_count: 1,
  batch_size: 1,
  hr_resize_mode: 'scale', // 'scale' 或 'size'，表示使用放大倍率或指定输出尺寸
  hr_target_width: 1024,  // 指定输出宽度
  hr_target_height: 1024  // 指定输出高度
}

const prompt = ref('')
const config = reactive({ ...defaultConfigTemplate })
const configName = ref('')
const selectedConfig = ref('')
const configList = ref<string[]>([])
const modelList = ref<string[]>([])
const loraModelList = ref<string[]>([])
const defaultConfigName = ref('')

// 设置默认配置
const handleSetDefault = async () => {
  if (!selectedConfig.value) return
  try {
    const response = await saveConfig({
      name: selectedConfig.value,
      ...config,
      is_default: true
    })
    if (response.data.success) {
      defaultConfigName.value = selectedConfig.value
    }
  } catch (error) {
    console.error('设置默认配置失败:', error)
  }
}

// 加载模型列表
const loadModelList = async () => {
  try {
    // 获取SD模型列表
    const modelResponse = await sdApi.getModels()
    if (modelResponse.data.success) {
      modelList.value = modelResponse.data.models || []
    }

    // 获取Lora模型列表
    const loraResponse = await sdApi.getLoraModels()
    if (loraResponse.data.success) {
      loraModelList.value = loraResponse.data.lora_models || []
    }
  } catch (error) {
    console.error('加载模型列表失败:', error)
  }
}

// 加载配置列表
const loadConfigList = async () => {
  try {
    const response = await listConfigs()
    if (response.data.success) {
      configList.value = response.data.configs
      // 如果有默认配置，自动加载
      if (response.data.default_config) {
        defaultConfigName.value = response.data.default_config
        await handleLoadConfig(response.data.default_config)
      }
    }
  } catch (error) {
    console.error('加载配置列表失败:', error)
  }
}

// 加载选中的配置
const handleLoadConfig = async (name: string) => {
  try {
    const response = await loadConfig(name)
    if (response.data.success) {
      Object.assign(config, response.data.config)
    }
  } catch (error) {
    console.error('加载配置失败:', error)
  }
}

// 保存当前配置
const handleSaveConfig = async () => {
  if (!configName.value.trim()) return
  try {
    const response = await saveConfig({
      name: configName.value,
      ...config,
      is_default: defaultConfigName.value === configName.value
    })
    if (response.data.success) {
      await loadConfigList()
      selectedConfig.value = configName.value
      configName.value = ''
    }
  } catch (error) {
    console.error('保存配置失败:', error)
  }
}

// 初始化时加载配置列表和模型列表
onMounted(() => {
  loadConfigList()
  loadModelList()
})

const handleGenerate = async () => {
  if (!prompt.value.trim() || !props.sdServiceAvailable) return

  // 直接传递配置名称，让后端加载对应配置
  emit('send', {
    prompt: prompt.value,
    config_name: selectedConfig.value || undefined,
    // 同时传递当前界面上的配置参数，如果有的话
    model: config.model,
    negative_prompt: config.negative_prompt,
    width: config.width,
    height: config.height,
    steps: config.steps,
    cfg_scale: config.cfg_scale,
    sampler_name: config.sampler_name,
    seed: config.seed,
    enable_hr: config.enable_hr,
    denoising_strength: config.denoising_strength,
    upscaler_scale: config.upscaler_scale,
    upscaler_name: config.upscaler_name,
    lora_model: config.lora_model,
    lora_weight: config.lora_weight,
    batch_count: config.batch_count,
    batch_size: config.batch_size,
    hr_resize_mode: config.hr_resize_mode,
    hr_target_width: config.hr_target_width,
    hr_target_height: config.hr_target_height
  })
  prompt.value = ''
}
</script>

<style scoped>
.sd-container {
  background: white;
  padding: 1rem;
  width: 100%;
  margin: 0 auto;
  display: flex;
  flex-direction: column;
  min-height: 0;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 0.5rem;
  padding-bottom: 0.5rem;
  border-bottom: 1px solid #ebeef5;
}

.header h2 {
  font-size: 1.5rem;
  color: var(--text-color);
  margin: 0;
}

.content {
  flex: 1;
  display: flex;
  flex-direction: row;
  min-height: 0;
  overflow: hidden;
}

.preview-area {
  flex: 0 0 30%;
  overflow-y: auto;
  padding-right: 1rem;
  border-right: 1px solid #ebeef5;
}

.message {
  margin-bottom: 1rem;
}

.prompt {
  padding: 0.5rem;
  background-color: #f5f7fa;
  border-radius: var(--border-radius);
  margin-bottom: 0.5rem;
}

.generated-image {
  max-width: 100%;
  border-radius: var(--border-radius);
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  margin-bottom: 1rem;
}

.config-area {
  flex: 0 0 70%;
  border-radius: var(--border-radius);
  overflow-y: auto;
  overflow-x: hidden;
  padding: 2rem;
}

.config-management {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin-bottom: 0.5rem;
}

.actions {
  margin-top: 0.5rem;
  text-align: right;
}

.form-item-help {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}

.output-size-display {
  font-size: 16px;
  font-weight: bold;
  color: #409EFF;
  text-align: center;
  padding: 8px;
  background-color: #ecf5ff;
  border-radius: var(--border-radius);
  border: 1px solid #d9ecff;
}
</style>
